package cn.tedu.tea.admin.server.product.service.impl;

import cn.tedu.tea.admin.server.common.consts.ContentConsts;
import cn.tedu.tea.admin.server.common.ex.ServiceException;
import cn.tedu.tea.admin.server.common.pojo.vo.PageData;
import cn.tedu.tea.admin.server.common.security.CurrentPrincipal;
import cn.tedu.tea.admin.server.common.web.ServiceCode;
import cn.tedu.tea.admin.server.content.dao.persist.repository.ICategoryRepository;
import cn.tedu.tea.admin.server.product.dao.persist.repository.IGoodsDetailRepository;
import cn.tedu.tea.admin.server.product.dao.persist.repository.IGoodsRepository;
import cn.tedu.tea.admin.server.product.pojo.entity.Goods;
import cn.tedu.tea.admin.server.product.pojo.entity.GoodsDetail;
import cn.tedu.tea.admin.server.product.pojo.param.GoodsAddNewParam;
import cn.tedu.tea.admin.server.product.pojo.vo.GoodsListItemVO;
import cn.tedu.tea.admin.server.product.pojo.vo.GoodsStandardVO;
import cn.tedu.tea.admin.server.product.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 处理商品数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 1.0
 */
@Slf4j
@Service
public class GoodsServiceImpl implements IGoodsService, ContentConsts {

    @Value("${tea-store.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private IGoodsRepository goodsRepository;
    @Autowired
    private ICategoryRepository categoryRepository;
    @Autowired
    private IGoodsDetailRepository goodsDetailRepository;

    public GoodsServiceImpl() {
        log.debug("创建业务类对象：GoodsServiceImpl");
    }

    @Override
    public void addNew(CurrentPrincipal currentPrincipal, String remoteAddr, GoodsAddNewParam goodsAddNewParam) {
        log.debug("开始处理【发布商品】的业务，当事人：{}，IP地址：{}，参数：{}", currentPrincipal, remoteAddr, goodsAddNewParam);

        // TODO 【检查类别是否存在】调用categoryRepository根据ID查询，如果结果为null则抛异常
        // TODO 【类别是否禁用】判断以上查询结果的enable，如果为0则抛异常
        // TODO 【检查是否非父级】判断以上查询结果的isParent，如果为1则抛异常

        Goods article = new Goods();
        BeanUtils.copyProperties(goodsAddNewParam, article);
        int rows = goodsRepository.insert(article);
        if (rows != 1) {
            String message = "发布商品失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        GoodsDetail articleDetail = new GoodsDetail();
        articleDetail.setId(article.getId());
        articleDetail.setDetail(goodsAddNewParam.getDetail());
        rows = goodsDetailRepository.insert(articleDetail);
        if (rows != 1) {
            String message = "发布商品失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除商品】的业务，参数：{}", id);
        GoodsStandardVO queryResult = goodsRepository.getStandardById(id);
        if (queryResult == null) {
            // 是：数据不存在，抛出异常
            String message = "删除商品失败，尝试删除的商品数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        int rows = goodsRepository.deleteById(id);
        if (rows != 1) {
            String message = "删除商品失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }

        rows = goodsDetailRepository.deleteByGoods(id);
        if (rows != 1) {
            String message = "删除商品失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
    }

    @Override
    public void putOn(Long id) {
        log.debug("开始处理【上架商品】的业务，参数：{}", id);
        updateStatusById(id, 1);
    }

    @Override
    public void pullOff(Long id) {
        log.debug("开始处理【下架商品】的业务，参数：{}", id);
        updateStatusById(id, 0);
    }

    @Override
    public GoodsStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询商品详情】的业务，参数：{}", id);
        GoodsStandardVO queryResult = goodsRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "查询商品详情失败，商品数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<GoodsListItemVO> list(Integer pageNum) {
        log.debug("开始处理【查询商品列表】的业务，页码：{}", pageNum);
        PageData<GoodsListItemVO> pageData = goodsRepository.list(pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<GoodsListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询商品列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageData<GoodsListItemVO> pageData = goodsRepository.list(pageNum, pageSize);
        return pageData;
    }

    @Override
    public PageData<GoodsListItemVO> listByCategoryId(Long categoryId, Integer pageNum) {
        log.debug("开始处理【根据商品类别查询商品列表】的业务，商品类别：{}, 页码：{}", categoryId, pageNum);
        PageData<GoodsListItemVO> pageData = goodsRepository.listByCategoryId(categoryId, pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<GoodsListItemVO> listByCategoryId(Long categoryId, Integer pageNum, Integer pageSize) {
        log.debug("开始处理【根据商品类别查询商品列表】的业务，商品类别：{}, 页码：{}，每页记录数：{}", categoryId, pageNum, pageSize);
        PageData<GoodsListItemVO> pageData = goodsRepository.listByCategoryId(categoryId, pageNum, pageSize);
        return pageData;
    }

    private void updateStatusById(Long id, Integer status) {
        GoodsStandardVO currentGoods = goodsRepository.getStandardById(id);
        if (currentGoods == null) {
            String message = "将商品状态修改为【" + STATUS_TEXT[status] + "】失败，商品数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (currentGoods.getStatus() == status) {
            String message = "将商品状态修改为【" + STATUS_TEXT[status] + "】失败，此商品已经处于" + STATUS_TEXT[status] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        Goods updateGoods = new Goods();
        updateGoods.setId(id);
        updateGoods.setStatus(status);
        int rows = goodsRepository.update(updateGoods);
        if (rows != 1) {
            String message = "将商品状态修改为【" + STATUS_TEXT[status] + "】失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

}